package com.hnld.transform.handler.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hnld.transform.cosntant.TransformConstant;
import com.hnld.transform.entity.IRIRoute;
import com.hnld.transform.entity.Parameter;
import com.hnld.transform.entity.RIRoute;
import com.hnld.transform.handler.IOtherFileHandler;
import com.hnld.transform.util.CSVFileUtils;
import org.apache.commons.io.filefilter.PrefixFileFilter;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

public class OtherRIFileHandler implements IOtherFileHandler {
    private static List<String> targets = Lists.newArrayList();
    private static Map<String, String> sourceMap = Maps.newHashMap();
    private static String routePath = "/路面图像/";

    static {
        //
        targets.add("DR");
        targets.add("IRI");
        targets.add("LBI");
        targets.add("RIFile");
        //对应的源文件夹目录
        sourceMap.put("DR", "/路面景象/识别结果/");
        sourceMap.put("IRI", "/平整度数据/IRI/");
        sourceMap.put("LBI", "/LBI/");
        sourceMap.put("RIFile", "/平整度数据/RIFile/");
    }

    @Override
    public String getType() {
        return "RIFile";
    }


    @Override
    public void handleFileType(List<File> files, String targetDir, String area, String areaRouteCode, Parameter parameter, Map<String, Integer> twoDirectionsMap) {
        System.out.println("处理区县【" + area + "】的路线【" + areaRouteCode + "】非图像类RI数据");
        //先把路线方向的最后的字母编号去掉
        String routeCode = areaRouteCode.substring(0, areaRouteCode.length() - 1);
        //RI文件在区县的路面平整度文件夹下
        String RIPath = parameter.getBaseSourcePath() + area + "/" + sourceMap.get(getType());
        //获取符合路线的文件
        List<File> riFiles = FileUtil.loopFiles(new File(RIPath), 3, new PrefixFileFilter(routeCode));

        //IRI文件在区县的路面平整度文件夹下
        String IRIPath = parameter.getBaseSourcePath() + area + "/" + sourceMap.get("IRI");
        List<File> sourceIRIFiles = FileUtil.loopFiles(IRIPath);

        List<File> fileList = sourceIRIFiles.stream().filter(sourceIRIFile -> sourceIRIFile.getName().startsWith(routeCode)).collect(Collectors.toList());//模糊
        if (CollectionUtil.isEmpty(fileList)) {
            System.out.println("未从区县【" + area + "】的路线【" + areaRouteCode + "】非图像类IRI数据中找到符合的RI路线数据");
            TransformConstant.RI_ROUTE.add(areaRouteCode);
            return;
        }
        List<File> IRIFileList = new ArrayList<>(); //存在多个文件
        //存在一条路线2个日期的RI文件夹，2个方向的IRI文件，所以要找出符合路线方向的IRI文件后，还要以IRI文件的时间戳去匹配
        for (File sourceIRIFile : fileList) {
            String name = sourceIRIFile.getName();
            List<IRIRoute> iriRoutes = CSVFileUtils.readCSVData(IRIPath + "/" + name, IRIRoute.class, true);
            if (CollectionUtil.isEmpty(iriRoutes)) {
                continue;
            }
            iriRoutes.stream().forEach(iriRoute -> {
                //获取一条数据里面的方向
                String direction = iriRoute.getDirection();
                String directionCode = TransformConstant.ROUTE_DIRECTION.get(direction);
                if (!twoDirectionsMap.isEmpty()) {
                    Integer integer = Optional.ofNullable(twoDirectionsMap.get(routeCode)).orElse(0);
                    //是否有两个方向
                    if (integer > 1) {
                        if (areaRouteCode.equals(routeCode + directionCode)) {
                            IRIFileList.add(sourceIRIFile);
                        }
                    } else {
                        IRIFileList.add(sourceIRIFile);
                    }
                } else {
                    IRIFileList.add(sourceIRIFile);
                }
            });

        }
        if (CollectionUtil.isEmpty(IRIFileList)) {
            System.out.println("未从区县【" + area + "】的路线【" + areaRouteCode + "】非图像类IRI数据中找到符合方向的RI路线数据");
            TransformConstant.RI_ROUTE.add(areaRouteCode);
            return;
        }

        List<String> iriNameSuffixList = new ArrayList<>();
        IRIFileList.stream().forEach(iriFile -> {
            //C00A431102-IRI-K0+000-20230729081204.csv
            String name = iriFile.getName();
            String[] iriNameSplit = name.split("-");
            //文件名后缀.csv去掉
            String iriNameSuffix = iriNameSplit[3].split("\\.")[0];
            iriNameSuffixList.add(iriNameSuffix);
        });

        //找到和IRIFile文件的时间戳相同的RI文件
        List<File> routeFilterList = riFiles.stream().filter(ri -> {
            String fileName = ri.getName();
            String[] nameSplit = fileName.split("-");
            //文件名后缀.csv去掉
            String nameSuffix = nameSplit[3].split("\\.")[0];
            return iriNameSuffixList.contains(nameSuffix);
        }).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(routeFilterList)) {
            System.out.println("未从区县【" + area + "】的路线【" + areaRouteCode + "】非图像类RI数据中找到符合时间戳的RI路线数据");
            TransformConstant.RI_ROUTE.add(areaRouteCode);
            return;
        }
        for (File riFile : routeFilterList) {
            //获取文件名 C161431102-LP-K0+000-20230718153752.csv  转换为 C161431102-LP-0.000-20230718153752.txt
            String fileName = riFile.getName();
            String[] nameSplit = fileName.split("-");
            //K0+000
            String stakeSegment = nameSplit[2];
            //转换成0.000
            stakeSegment = stakeSegment.replace("K", "").replace("+", ".");
            //文件名后缀.csv去掉
            String nameSuffix = nameSplit[3].split("\\.")[0];
            String newFileName = areaRouteCode + "-" + nameSplit[1] + "-" + stakeSegment + "-" + nameSuffix + ".txt";
            writeCSVData(riFile, targetDir + "\\" + newFileName);
        }

    }

    private static void writeCSVData(File riFile, String targetPath) {
        List<String> writeContent = new ArrayList<>();
        List<RIRoute> riRoutes = CSVFileUtils.readCSVData(riFile.getAbsolutePath(), RIRoute.class, false);
        List<String> titleList = CSVFileUtils.getTitleList(RIRoute.class, TransformConstant.excludeTitle, "", -1);
        String titleContent = String.join(",", titleList);
        writeContent.add(titleContent);
        riRoutes.forEach(data -> {
            if (StringUtils.isBlank(data.getStake())) {
                return;
            }
            //拼接内容
            //桩号格式变更 K0+000.0 ->0.0000
            String stake = data.getStake();
            //替换K
            stake = stake.replace("K", "");
            //替换.
            stake = stake.replace(".", "");
            //替换+
            stake = stake.replace("+", ".");
            //起点桩号(km),左高程(mm),右高程(mm),速度(m/s)
            String content = stake + "," + data.getLeftElevation() + "," + data.getRightElevation() + "," + data.getSpeed();
            writeContent.add(content);
        });
        //写入文件
        FileUtil.writeLines(writeContent, targetPath, Charset.defaultCharset());
    }


}
